package cn.bearspark.user.provider.service.impl;

import cn.bearspark.common.util.DataUtil;
import cn.bearspark.user.dto.UserAtDTO;
import cn.bearspark.user.provider.dao.buffer.UserIdNameBuffer;
import cn.bearspark.user.provider.dao.mapper.UserAtMapper;
import cn.bearspark.user.provider.dao.po.UserAtPO;
import cn.bearspark.user.provider.service.UserAtService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author f
 */
@Service
public class UserAtServiceImpl implements UserAtService {

    private final UserAtMapper userAtMapper;

    private final UserIdNameBuffer userIdNameBuffer;

    public UserAtServiceImpl(UserAtMapper userAtMapper,
                             UserIdNameBuffer userIdNameBuffer) {
        this.userAtMapper = userAtMapper;
        this.userIdNameBuffer = userIdNameBuffer;
    }

    @Override
    public void addAtUsernameList(int moduleCode, long moduleDataId, List<String> atUsernameList) {
        // 将用户名转换成用户 id
        Map<String, Long> idNameMap = userIdNameBuffer.map(atUsernameList);

        // 批量添加数据
        userAtMapper.insertBatchUserAt(moduleCode, moduleDataId, atUsernameList.stream().map(idNameMap::get).toList());
    }

    @Override
    public Map<Long, List<UserAtDTO>> mapAtUsernameSet(int moduleCode, Set<Long> moduleDataIdSet) {
        return DataUtil.group(
                moduleDataIdSet.size(),
                UserAtDTO.class,
                () -> userAtMapper.list(moduleCode, moduleDataIdSet),
                UserAtPO::getModuleDataId
        );
    }

    @Override
    public void delete(int moduleCode, long moduleDataId) {
        userAtMapper.delete(moduleCode, moduleDataId);
    }
}
